package com.qf.commons.web.exception.handler;


import com.qf.commons.standar.exception.IExceptionHandler;
import com.qf.data.base.r.Codes;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class BindExceptionHandler implements IExceptionHandler {
    @Override
    public boolean isSupport(Exception e) {
        return e.getClass() == BindException.class || e.getClass()== ConstraintViolationException.class;
    }

    @Override
    public R exceptionHandler(Exception e) {
        Map<String,String> result=null;
        if (e instanceof BindException){
            BindException bindException = (BindException) e;
            result = bindException.getAllErrors().stream()
                    .collect(Collectors.toMap(
                            objectError -> objectError.getCodes()[1],
                            objectError -> objectError.getDefaultMessage()
                    ));
        }else if (e instanceof ConstraintViolationException){
            ConstraintViolationException conException= (ConstraintViolationException) e;
            result = conException.getConstraintViolations().stream()
                    .collect(Collectors.toMap(
                            constraintViolation -> constraintViolation.getPropertyPath().toString(),
                            ConstraintViolation::getMessageTemplate
                    ));
        }
        return Rs.createFail(Codes.PARAM_ERROR,result);
    }
}
